from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from django.contrib.auth import login, logout
from apps.users.models import User
from django_redis import get_redis_connection
import json
import re


# Create your views here.

class UsernameCountView(View):
    """判断用户名是否重复注册"""

    def get(self, request, username):
        """
        :param request: 请求对象
        :param username: 用户名
        :return: JSON
        """
        count = User.objects.filter(username=username).count()
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'count': count})


class MobileCountView(View):
    """判断手机号是否重复注册"""

    def get(self, request, mobile):
        """
        :param request: 请求对象
        :param mobile: 手机号
        :return: JSON
        """
        count = User.objects.filter(mobile=mobile).count()
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'count': count})


class RegisterView(View):
    """用户注册"""

    def post(self, request):
        """
        实现用户注册
        :param request: 请求对象
        :return: 注册结果
        """
        # 1.接收参数：请求体中的JSON数据 request.body
        # json_bytes = request.body  # 从请求体中获取原始的JSON数据，bytes类型的
        # print(json_bytes)
        # print('#'*40)
        # json_str = json_bytes.decode()  # 将bytes类型的JSON数据，转成JSON字符串
        # print(json_str)
        # json_dict = json.loads(json_str)  # 将JSON字符串转成python的标准字典
        # json_dict = json.loads(request.body.decode())
        json_dict = request.POST

        # 提取参数
        username = json_dict.get('username')
        print(username)
        password = json_dict.get('password')
        password2 = json_dict.get('password2')
        mobile = json_dict.get('mobile')
        allow = json_dict.get('allow')
        sms_code = json_dict.get('sms_code')

        # 2.校验参数
        # 判断参数是否齐全
        if not all([username, password, password2, mobile, allow, sms_code]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必要参数'})
        # 判断用户名是否是5-20个字符
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return JsonResponse({'code': 400, 'errmsg': '用户名格式有误'})
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return JsonResponse({'code': 400, 'errmsg': '密码格式有误！'})
        # 判断两次密码是否一致
        if password != password2:
            return JsonResponse({'code': 400, 'errmsg': '两次密码不一致'})
        # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': '手机号码格式有误'})
        # 判断用户是否勾选用户协议
        if allow != True:
            return JsonResponse({'code': 400, 'errmsg': '未同意用户协议'})

        redis_conn = get_redis_connection('code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)

        # 判断短信验证码是否过期
        if not sms_code_server:
            return JsonResponse({'code': 400, 'errmsg': '短信验证码失效'})
        # 对比用户输入的短信验证码与服务端存储的短信验证码是否一致
        if sms_code != sms_code_server.decode():
            return JsonResponse({'code': 400, 'errmsg': '短信验证码有误'})
        # 3.保存注册数据，返回响应
        try:
            user = User.objects.create_user(username=username,
                                            password=password,
                                            mobile=mobile)
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '注册失败'})

        # 事故下班状态保持
        login(request, user)

        # 响应注册结果
        return JsonResponse({'code': 400, 'errmsg': '注册成功'})
